"use strict";
var TokensService_1 = require('../services/TokensService');
var BaseController = (function () {
    function BaseController(app) {
        this.domain = "/kapi";
        this.app = app;
        this.tokensService = new TokensService_1.TokensService();
    }
    BaseController.prototype.initResponse = function (res) {
        res.header("Content-Type", "application/json");
        res.header('Access-Control-Allow-Origin', '*');
        res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type,Content-Length, Accept,Referer,Accept-Language,User-Agent,x-token,x-username,x-password');
        res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
    };
    BaseController.prototype.validateUser = function (req, res, success, fail) {
        var tokenStr = req.header("x-token");
        this.tokensService.get(tokenStr, function (err, user) {
            if (user !== undefined) {
                success(user);
            }
            else {
                fail && fail();
                if (!fail) {
                    res.send({ msg: "auth is error!" });
                }
            }
        });
    };
    BaseController.prototype.handerErr = function (req, res, handler, checkToken) {
        try {
            this.initResponse(res);
            var contenttype = req.header("Content-Type") || "";
            contenttype = contenttype.toLowerCase();
            if (contenttype.indexOf("application/json") < 0 && req.method.toLowerCase() != "get" && req.method.toLowerCase() != "delete" && req.method.toLowerCase() != "options") {
                res.statusCode = 400;
                res.send({ msg: "Please set Request Content-Type is application/json." });
                return;
            }
            if (checkToken) {
                this.validateUser(req, res, function (user) {
                    handler && handler(user);
                });
            }
            else {
                handler && handler();
            }
        }
        catch (ex) {
            console.log(ex);
            console.log(ex.stack);
            res.statusCode = 500;
            res.send({ msg: "server have a error!" });
        }
    };
    return BaseController;
}());
exports.BaseController = BaseController;
